//
//  NSString+XMGExtension.m

//  商信
//
//  Created by zhangjianhong on 16/7/2.
//  Copyright © 2016年 zhangjianhong. All rights reserved.


#import "NSString+XMGExtension.h"
#import<CommonCrypto/CommonDigest.h>
#import "WJCDefine.h"
@implementation NSString (XMGExtension)

    /// 判断是否含有小写字母
- (BOOL)hasLowerEnglishCharacter {

//    NSString *lowerRegex = @"^[\\u0061-\\u007A]+$";
//
//    BOOL isEnglish = [self rangeOfString:lowerRegex options:NSRegularExpressionSearch].length>0;
//    NSString* const pattern = @"^.*(?=.{6,})(?=.*[a-z])(?=.*[A-Z]).*$";
    NSString* const pattern = @"^.*(?=.*[a-z]).*$";
      NSRegularExpression* regex = [[NSRegularExpression alloc] initWithPattern:pattern options:0 error:nil];
      NSRange range = NSMakeRange(0, [self length]);
      return [regex numberOfMatchesInString:self options:0 range:range] > 0;
}

    /// 判断是否含有大写字母
- (BOOL)hasUpperrEnglishCharacter {

    NSString* const pattern = @"^.*(?=.*[A-Z]).*$";
          NSRegularExpression* regex = [[NSRegularExpression alloc] initWithPattern:pattern options:0 error:nil];
          NSRange range = NSMakeRange(0, [self length]);
          return [regex numberOfMatchesInString:self options:0 range:range] > 0;
}
    /// 判断是否含有字符
- (BOOL)hasSymbolCharacter {
//    \\u4e00-\\u9fa5_a-zA-Z0-9\\s
    NSString* const pattern = @"^[\\·\\~\\！\\@\\#\\￥\\%\\……\\&\\*\\（\\）\\——\\-\\+\\=\\【\\】\\{\\}\\、\\|\\；\\‘\\’\\：\\“\\”\\《\\》\\？\\，\\。\\、\\`\\~\\!\\#\\$\\%\\^\\&\\*\\(\\)\\_\\[\\]{\\}\\\\|\\;\\'\\'\\:\\\"\\\"\\,\\.\\/\\<\\>\\?]+$";
          NSRegularExpression* regex = [[NSRegularExpression alloc] initWithPattern:pattern options:0 error:nil];
          NSRange range = NSMakeRange(0, [self length]);
          return [regex numberOfMatchesInString:self options:0 range:range] > 0;
}

/**
* 功能：校验手机号码
*/
- (BOOL)isPhone
{
    return [self isMobileNumberClassification];
//    /**
//     * 手机号码
//     * 移动：134[0-8],135,136,137,138,139,150,151,157,158,159,182,187,188,183,184,178
//     * 联通：130,131,132,152,155,156,185,186
//     * 电信：133,1349,153,180,189,181,177
//     */
//    NSString * MOBILE = @"^1(3[0-9]|5[0-35-9]|70|8[0-9])\\d{8}$";
//    /**
//     10         * 中国移动：China Mobile
//     11         * 134[0-8],135,136,137,138,139,150,151,157,158,159,182,187,188,183,184,178
//     12         */
//    NSString * CM = @"^1(34[0-8]|(3[5-9]|5[017-9]|78|8[2-478])\\d)\\d{7}$";
//    /**
//     15         * 中国联通：China Unicom
//     16         * 130,131,132,152,155,156,185,186,176
//     17         */
//    NSString * CU = @"^1(3[0-2]|5[256]|76|8[56])\\d{8}$";
//    /**
//     20         * 中国电信：China Telecom
//     21         * 133,1349,153,180,181,189,177,173
//     22         */
//    NSString * CT = @"^1((33|53|73|77|8[019])[0-9]|349)\\d{7}$";
//
//    NSPredicate *regextestmobile = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", MOBILE];
//    NSPredicate *regextestcm = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CM];
//    NSPredicate *regextestcu = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CU];
//    NSPredicate *regextestct = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CT];
//
//    if (([regextestmobile evaluateWithObject:self] == YES)
//        || ([regextestcm evaluateWithObject:self] == YES)
//        || ([regextestct evaluateWithObject:self] == YES)
//        || ([regextestcu evaluateWithObject:self] == YES))
//    {
//        return YES;
//    }
//    else
//    {
//        return NO;
//    }
}
    /// 是否包含数字
- (BOOL)hasNumber {

    NSString* const pattern = @"^.*(?=.*[0-9]).*$";
          NSRegularExpression* regex = [[NSRegularExpression alloc] initWithPattern:pattern options:0 error:nil];
          NSRange range = NSMakeRange(0, [self length]);
          return [regex numberOfMatchesInString:self options:0 range:range] > 0;

}
+ (NSString *)changeArr2StrWithArr:(NSArray*)arr :(NSString*)str{
    NSString *s =[arr componentsJoinedByString:str];
    return s;
}
- (BOOL)isUrl {
    
    if(self == nil) {
        return NO;
    }
    
    NSString *url;
    if (self.length>4 && [[self substringToIndex:4] isEqualToString:@"www."]) {
        url = [NSString stringWithFormat:@"%@://%@",@"https",self];
    }else{
        url = self;
    }
      NSString *urlRegex = @"\\b((?:https?://|[a-z0-9.\\-]+[.]|[a-z0-9.\\-]+[.][a-z]{2,4}/)(?:[^\\s()<>]+|\\(([^\\s()<>]+|(\\([^\\s()<>]+\\)))*\\))+(?:\\(([^\\s()<>]+|(\\([^\\s()<>]+\\)))*\\)|[^\\s`!()\\[\\]{};:'\".,<>???“”‘’]))";
    NSPredicate* urlTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", urlRegex];
    BOOL isurl=[urlTest evaluateWithObject:url];
    return isurl;
}
-(NSString *)isPhoneSecret{
    if (!self) {
        return self;
    }
    NSMutableString *str = self.mutableCopy;
    if ([self isPhone]) {
       
        if (str.length==11) {
            [str replaceCharactersInRange:NSMakeRange(3, 1) withString:@"*"];
            [str replaceCharactersInRange:NSMakeRange(4, 1) withString:@"*"];
            [str replaceCharactersInRange:NSMakeRange(5, 1) withString:@"*"];
            [str replaceCharactersInRange:NSMakeRange(6, 1) withString:@"*"];
           
        }
       
    }
        return str;
}
// 判断一个路径是文件夹 or 文件
//    [[mgr attributesOfItemAtPath:self error:nil].fileType isEqualToString:NSFileTypeDirectory];

- (NSInteger)fileSize
{
    // 文件管理者
    NSFileManager *mgr = [NSFileManager defaultManager];
    // 是否为文件夹
    BOOL isDirectory = NO;
    // 这个路径是否存在
    BOOL exists = [mgr fileExistsAtPath:self isDirectory:&isDirectory];
    // 路径不存在
    if (exists == NO) return 0;
    
    if (isDirectory) { // 文件夹
        // 总大小
        NSInteger size = 0;
        // 获得文件夹中的所有内容
        NSDirectoryEnumerator *enumerator = [mgr enumeratorAtPath:self];
        for (NSString *subpath in enumerator) {
            // 获得全路径
            NSString *fullSubpath = [self stringByAppendingPathComponent:subpath];
            // 获得文件属性
            size += [mgr attributesOfItemAtPath:fullSubpath error:nil].fileSize;
        }
        return size;
    } else { // 文件
        return [mgr attributesOfItemAtPath:self error:nil].fileSize;
    }
}
-(CGFloat)stringWidthWithFont:(UIFont *)font{
    return [self sizeWithFont:font maxW:10000].width;
}
- (CGSize)sizeWithFont:(UIFont *)font maxW:(CGFloat)maxW
{
    NSMutableDictionary *attrs = [NSMutableDictionary dictionary];
    attrs[NSFontAttributeName] = font;
    CGSize maxSize = CGSizeMake(maxW, MAXFLOAT);
    
    return [self boundingRectWithSize:maxSize options:NSStringDrawingUsesLineFragmentOrigin attributes:attrs context:nil].size;
   
}
- (CGSize)sizeWithFontSize:(CGFloat)fontSize maxW:(CGFloat)maxW lineBreakMode:(NSLineBreakMode)lineBreakMode{
    NSMutableParagraphStyle *style = [[NSMutableParagraphStyle alloc] init];
    [style setLineBreakMode:lineBreakMode];
    CGSize maxSize = CGSizeMake(maxW, MAXFLOAT);
    
    return [self boundingRectWithSize:maxSize options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:fontSize], NSParagraphStyleAttributeName:style} context:nil].size;
}

- (CGSize)sizeWithMyFont:(UIFont *)font
{
    return [self sizeWithFont:font maxW:MAXFLOAT];
}

//传入省，返回中国
+ (NSString *)returnChina:(NSString *)province
{
    if ([province hasPrefix:@"北京"]||[province hasPrefix:@"天津"]||[province hasPrefix:@"上海"]||[province hasPrefix:@"重庆"]||[province hasPrefix:@"台湾"]||[province hasPrefix:@"香港"]||[province hasPrefix:@"澳门"]||[province hasSuffix:@"省"]||[province hasSuffix:@"自治区"]||[province hasSuffix:@"行政区"]) {
       return @"中国 ";
        
    } else {
        return @"";
    }

}

// 截取字符串中两个指定字符串中间的字符串
- (NSString *)subStringFrom:(NSString *)startString to:(NSString *)endString{
    
    NSRange startRange = [self rangeOfString:startString options:NSCaseInsensitiveSearch];
    NSRange endRange = [self rangeOfString:endString];
    
    if (startRange.location != NSNotFound && endRange.location != NSNotFound) {
       
         NSRange range = NSMakeRange(startRange.location + startRange.length, endRange.location - startRange.location - startRange.length);
        
         return [self substringWithRange:range];
    }

    return @"";
    
}

/**
 *  URLEncode
 */
- (NSString *)URLEncodedString
{
    // CharactersToBeEscaped = @":/?&=;+!@#$()~',*";
    // CharactersToLeaveUnescaped = @"[].";
    
    NSString *unencodedString = self;
    NSString *encodedString = (NSString *)
    CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault,
                                                              (CFStringRef)unencodedString,
                                                              NULL,
                                                              (CFStringRef)@"!*'();:@&=+$,/?%#[]",
                                                              kCFStringEncodingUTF8));
    
    return encodedString;
}

/**
 *  URLDecode
 */
-(NSString *)URLDecodedString
{
    //NSString *decodedString = [encodedString stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding ];
    
    NSString *encodedString = self;
    NSString *decodedString  = (__bridge_transfer NSString *)CFURLCreateStringByReplacingPercentEscapesUsingEncoding(NULL,
                                                                                                                     (__bridge CFStringRef)encodedString,
                                                                                                                     CFSTR(""),
                                                                                                                     CFStringConvertNSStringEncodingToEncoding(NSUTF8StringEncoding));
    return decodedString;
}

/**
 *  md5加密
 */
- (NSString *)md5
{
    const char *newStr = [self UTF8String];
    
    unsigned char result[CC_MD5_DIGEST_LENGTH];
    
    CC_MD5(newStr,(unsigned int)strlen(newStr),result);
    
    NSMutableString *outStr = [NSMutableString stringWithCapacity:CC_MD5_DIGEST_LENGTH];
    
    for(int i = 0;i<CC_MD5_DIGEST_LENGTH;i++){
        
        [outStr appendFormat:@"%02x",result[i]];//注意：这边如果是x则输出32位小写加密字符串，如果是X则输出32位大写字符串
    }
    return outStr;
}
+(NSString *)translatByKVCWithKey:(NSString *)key andReplaceArray:(NSArray *)arr{
    NSMutableString *urlStr =[NSMutableString stringWithFormat:@"%@", key];
    for (int i = 0; i < arr.count; i++) {
         NSRange range = [urlStr rangeOfString:@"%s"];
        if (range.location != NSNotFound) {
            [urlStr replaceCharactersInRange:range withString:[NSString stringWithFormat:@"%@",arr[i]]];
        }
    }
    return urlStr;
}
+(languageType)returnCurrentLanguage{
    NSString *currentLanguage=[[NSUserDefaults standardUserDefaults] objectForKey:@"appLanguage"];
    if ([currentLanguage isEqualToString:@"zh-Hans"]) {//判断是不是中文
        return languageZH;
    }else if ([currentLanguage containsString:@"en"]) {//判断是不是中文
        return languageEn;
    }else{
        return languageUnknow;
    }
}


#pragma mark 计算字符串大小
+ (BOOL)isBlankString:(NSString *)string{
    if (string == nil || string == NULL || [string  isEqual: @" "]|| [string  isEqual: @"(null)"]|| [string  isEqual: @""]) {
        return YES;
    }
    if ([string isKindOfClass:[NSNull class]]) {
        return YES;
    }
    return NO;
}
+(NSString *)getYearTime{
    NSDate *date = [NSDate date];
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    
    [formatter setDateStyle:NSDateFormatterMediumStyle];
    
    [formatter setTimeStyle:NSDateFormatterShortStyle];
    
    [formatter setDateFormat:@"YYYY"];
    NSString *DateTime = [formatter stringFromDate:date];
    return DateTime;
}

+ (NSString *)getCurrentTime{
    NSDate *date = [NSDate date];
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    
    [formatter setDateStyle:NSDateFormatterMediumStyle];
    
    [formatter setTimeStyle:NSDateFormatterShortStyle];
    
    [formatter setDateFormat:@"yyyy-MM-dd"];
    NSString *DateTime = [formatter stringFromDate:date];
    return DateTime;
}

+ (NSString *)getYearDateTime{
    NSDate *date = [NSDate date];
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    
    [formatter setDateStyle:NSDateFormatterMediumStyle];
    
    [formatter setTimeStyle:NSDateFormatterShortStyle];
    
    [formatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss+H:mm"];
    NSString *DateTime = [formatter stringFromDate:date];
    return DateTime;
}

+(NSString *)stringWithTransformationTime:(NSDate *)timeDate{
    NSDateFormatter *forma = [[NSDateFormatter alloc]init];
    [forma setDateFormat:@"yyyy-MM-dd"];
    NSString *timeStr = [forma stringFromDate:timeDate];
    return timeStr;
}
    //+(NSString *)stringWithTime:(NSDate *)timeDate{
    //    NSDateFormatter *forma = [[NSDateFormatter alloc]init];
    //    [forma setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    //    NSString *timeStr = [forma stringFromDate:timeDate];
    //    return timeStr;
    //}
+(NSString *)stringWithBirthday:(NSDate *)timeDate{
    NSDateFormatter *forma = [[NSDateFormatter alloc]init];
    [forma setDateFormat:@"yyyy-MM-dd"];
    
    NSString *currentDateStr = [forma stringFromDate:[NSDate date]];
    NSDate *currentDate = [forma dateFromString:currentDateStr];
    NSTimeInterval time=[currentDate timeIntervalSinceDate:timeDate];
    int age = ((int)time)/(3600*24*365);
    NSString *ageStr =[NSString stringWithFormat:@"%d",age];
    return ageStr;
}
+ (id)toArrayOrNSDictionary:(NSString *)jsonStr{
    
      if (jsonStr) {
                id tmp = [NSJSONSerialization JSONObjectWithData:[jsonStr dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingAllowFragments | NSJSONReadingMutableLeaves | NSJSONReadingMutableContainers error:nil];
                
                if (tmp) {
                        if ([tmp isKindOfClass:[NSArray class]]) {
                                
                                return tmp;
                                
                            } else if([tmp isKindOfClass:[NSString class]]
                                                            || [tmp isKindOfClass:[NSDictionary class]]) {
                                    
                                    return [NSArray arrayWithObject:tmp];
                                    
                                } else {
                                        return nil;
                                    }
                    } else {
                            return nil;
                        }
                
            } else {
                    return nil;
                }
  
    
}

+ (NSString *)toJson:(id)anyObject{
    
    if ([NSJSONSerialization isValidJSONObject:anyObject])
        {
        NSError *error;
        
        NSData *data = [NSJSONSerialization dataWithJSONObject:anyObject options:NSJSONWritingPrettyPrinted error:&error];
        NSString *str =[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
        str = [str stringByReplacingOccurrencesOfString:@"\n" withString:@""];
        str = [str stringByReplacingOccurrencesOfString:@" " withString:@""];
        return str;
        }
    
    return nil;
}
+ (NSString *)getBabyDetailAge:(NSString *)date
{
    NSDateFormatter *stampFormatter = [[NSDateFormatter alloc] init];
    [stampFormatter setDateFormat:@"yyyy-MM-dd "];
    NSDate *stampDate2 = [NSDate dateWithTimeIntervalSince1970:[date longLongValue]];
    
    return [stampFormatter stringFromDate:stampDate2];
    
}

+ (NSString *)getCurrentTimeStamp {
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateStyle:NSDateFormatterMediumStyle];
    [formatter setTimeStyle:NSDateFormatterShortStyle];
    [formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"]; // ----------设置你想要的格式,hh与HH的区别:分别表示12小时制,24小时制
    
        //设置时区,这个对于时间的处理有时很重要
    NSTimeZone* timeZone = [NSTimeZone timeZoneWithName:@"Asia/Beijing"];
    [formatter setTimeZone:timeZone];
    NSDate *datenow = [NSDate date];//现在时间
    
        //时间转时间戳的方法:
    NSInteger timeSp = [[NSNumber numberWithDouble:[datenow timeIntervalSince1970]] integerValue];
    NSString *ts = [NSString stringWithFormat:@"%ld",(long)timeSp];//时间戳的值
    return ts;
}
+ (NSString *)getDateStringWithTimeStr:(NSString *)str{
    NSTimeInterval time=[str doubleValue];//传入的时间戳str如果是精确到毫秒的记得要/1000
    NSDate *detailDate=[NSDate dateWithTimeIntervalSince1970:time];
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; //实例化一个NSDateFormatter对象
                                                                     //设定时间格式,这里可以设置成自己需要的格式
    [dateFormatter setDateFormat:@"yyyy-MM-dd"];
    NSString *currentDateStr = [dateFormatter stringFromDate: detailDate];
    return currentDateStr;
}

+ (NSString *)getDateStringWithTimeStr2:(NSString *)str2{
    NSTimeInterval time=[str2 doubleValue];//传入的时间戳str如果是精确到毫秒的记得要/1000
    NSDate *detailDate=[NSDate dateWithTimeIntervalSince1970:time];
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; //实例化一个NSDateFormatter对象
                                                                     //设定时间格式,这里可以设置成自己需要的格式
    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm"];
    NSString *currentDateStr = [dateFormatter stringFromDate: detailDate];
    return currentDateStr;
}

/**
  传入时间戳，返回月日时

 @param str 时间戳
 @return 月日时
 */
+ (NSString *)getTimeWihtMDHMWihtStr:(NSString *)str{
    NSTimeInterval time=[str doubleValue];//传入的时间戳str如果是精确到毫秒的记得要/1000
    NSDate *detailDate=[NSDate dateWithTimeIntervalSince1970:time];
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; //实例化一个NSDateFormatter对象
    //设定时间格式,这里可以设置成自己需要的格式
    [dateFormatter setDateFormat:@"MM/dd HH:mm"];
    NSString *currentDateStr = [dateFormatter stringFromDate: detailDate];
    return currentDateStr;
}
/**
 
  * 开始到结束的时间差
 
  */

+ (NSString *)dateTimeDifferenceWithStartTime:(NSString *)startTime endTime:(NSString *)endTime{
    
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd"];
    NSDate *startDate = [dateFormatter dateFromString:startTime];
    NSDate *endDate = [dateFormatter dateFromString:endTime];
    
        //利用NSCalendar比较日期的差异
    NSCalendar *calendar = [NSCalendar currentCalendar];
    /**
     * 要比较的时间单位,常用如下,可以同时传：
     *    NSCalendarUnitDay : 天
     *    NSCalendarUnitYear : 年
     *    NSCalendarUnitMonth : 月
     *    NSCalendarUnitHour : 时
     *    NSCalendarUnitMinute : 分
     *    NSCalendarUnitSecond : 秒
     */
    NSCalendarUnit unit = NSCalendarUnitDay;//只比较天数差异
                                            //比较的结果是NSDateComponents类对象
    NSDateComponents *delta = [calendar components:unit fromDate:startDate toDate:endDate options:0];
        //打印
        //获取其中的"天"
    
    
    return [NSString stringWithFormat:@"%ld",delta.day];
    
}
    //将时间数据（毫秒）转换为天和小时
+ (NSString*)getOvertime:(NSString*)mStr
{
    long msec = [mStr longLongValue];
    
    if (msec <= 0)
        {
        return @"";
        }
    
    NSInteger d = msec/60/60/24;
    NSInteger h = msec/60/60%24;
    NSInteger  m = msec/60%60;
    NSInteger  s = msec%60;
    
    NSString *_tStr = @"";
    NSString *_dStr = @"";
    NSString *_hStr = @"";
    NSString *_mStr = @"";
    NSString *_sStr = @"";
    if (d > 0)
        {
        _dStr = [NSString stringWithFormat:@"%ld天",d];
        }
    
    if (h > 0)
        {
        _hStr = [NSString stringWithFormat:@"%ld小时",h];
        }
    if (m > 0)
        {
        _mStr = [NSString stringWithFormat:@"%ld分",m];
        }
    if (s > 0)
        {
        _sStr = [NSString stringWithFormat:@"%ld秒",s];
        }
    
    _tStr = [NSString stringWithFormat:@"%@%@%@%@后到期",_dStr,_hStr,_mStr,_sStr];
    
    return _tStr;
}
#define packagelocaChanged(key , annotation)  [NSBundle localizedStringForKey:key value:annotation andBundleClass:[self class] andBundleName:@"package"]
+(NSString*)outPutNimErrorWithErrorCode:(NSInteger)code{
    switch (code) {
        case 200:
            return @"操作成功";
            break;
        case 201:
            return  @"版本升级";//packagelocaChanged(@"common_upgrade_low_version", @"版本升级");//@"客户端版本不对，需升级sdk";
            break;
        case 301:
            return @"被封禁";//packagelocaChanged(@"common_im_forbid_talk", @"被封禁");
            break;
        case 302:
            return @"用户名或密码错误";//packagelocaChanged(@"access_incorrect_username_pwd", @"用户名或密码错误");//@"用户名或密码错误";
            break;
        case 315:
            return  @"IP限制";
            break;
        case 403:
            return  @"非法操作或没有权限";//packagelocaChanged(@"global_ios_prompt_five", @"非法操作或没有权限");//@"非法操作或没有权限";
            break;
        case 404:
            return @"对象不存在";//packagelocaChanged(@"common_im_member_none", @"对象不存在");//@"对象不存在";
            break;
        case 405:
            return @"参数长度过长";
            break;
        case 406:
            return @"对象只读";
            break;
        case 408:
            return @"客户端请求超时";//packagelocaChanged(@"oa_worktask_status_time_out", @"客户端请求超时");//@"客户端请求超时";
            break;
        case 413:
            return @"验证失败(短信服务)";
            break;
        case 414:
            return @"参数错误";
            break;
        case 415:
            return @"客户端网络问题";//packagelocaChanged(@"global_ios_prompt3_seventy_nine", @"客户端网络问题");//@"客户端网络问题";
            break;
        case 416:
            return @"频率控制";
            break;
        case 417:
            return  @"重复操作";//packagelocaChanged(@"crm_customer_reminder_repeat", @"重复操作");//@"重复操作";
            break;
        case 418:
            return @"通道不可用(短信服务)";
            break;
        case 419:
            return @"数量超过上限";
            break;
        case 422:
            return @"账号被禁用";
            break;
        case 431:
            return @"HTTP重复请求";
            break;
        case 500:
            return @"服务器内部错误";
            break;
        case 503:
            return @"服务器繁忙";
            break;
        case 508:
            return @"消息撤回时间超限";
            break;
        case 509:
            return @"无效协议";
            break;
        case 514:
            return @"服务不可用";
            break;
        case 998:
            return @"解包错误";
            break;
        case 999:
            return @"打包错误";
            break;
                //群相关
        case 801:
            return @"群人数达到上限";//packagelocaChanged(@"common_im_group_500_persons", @"群人数达到上限");//@"群人数达到上限";
            break;
        case 802:
            return @"没有权限";
            break;
        case 803:
            return @"群不存在";
            break;
        case 804:
            return @"用户不在群";
            break;
        case 805:
            return @"群类型不匹配";
            break;
        case 806:
            return @"创建群数量达到限制";
            break;
        case 807:
            return @"群成员状态错误";
            break;
        case 808:
            return @"申请成功";
            break;
        case 809:
            return @"已经在群内";
            break;
        case 810:
            return @"邀请成功";//packagelocaChanged(@"global_ios_prompt_invite_successful", @"邀请成功");
            break;
                //音频相关
        case 9102:
            return @"通道失效";
            break;
        case 9103:
            return @"已经在他端对这个呼叫响应过了";
            break;
        case 11001:
            return @"通话不可达，对方离线状态";
            break;
                //聊天室相关错误
        case 13001:
            return @"IM主连接状态异常";
        case 13002:
            return @"聊天室状态异常";
        case 13003:
            return @"账号在黑名单中,不允许进入聊天室";
        case 13004:
            return @"在禁言列表中,不允许发言";
                //特定业务
        case 10431:
            return @"输入email不是邮箱";
            break;
        case 10432:
            return @"输入mobile不是手机号码";
        case 10433:
            return @"注册输入的两次密码不相同";
        case 10434:
            return @"企业不存在";
        case 10435:
            return @"登陆密码或账号不对";
        case 10436:
            return @"app不存在";
        case 10437:
            return @"email已注册";
        case 10438:
            return @"手机号已注册";
        case 10441:
            return @"app名字已经存在";
        default:
            return @"未知错误";
            break;
    }
}

#pragma mark - size转字符串
+ (NSString *)convertSize:(long long)size {
    if (size < 1024) {
        return [NSString stringWithFormat:@"%lldB",size];
    } else if (size >= 1024 && size < 1024*1024) {
        return [NSString stringWithFormat:@"%.0fKB",(float)size/1024];
    } else if (size >= 1024*1024 && size < 1024*1024*1024) {
        return [NSString stringWithFormat:@"%.1fMB",(float)size/(1024*1024)];
    } else {
        return [NSString stringWithFormat:@"%.1fG",(float)size/(1024*1024*1024)];
    }
}

#pragma mark - 拓展名输出本地图片
+ (NSString *)convertImageExt:(NSString *)ext
{
    if ([ext.lowercaseString isEqualToString:@"jpg"] || [ext.lowercaseString isEqualToString:@"jpeg"] || [ext.lowercaseString isEqualToString:@"png"]) {
        return @"ic_company_cloud_photo";
    } else if ([ext.lowercaseString isEqualToString:@"ae"]) {
        return @"ic_company_cloud_ae";
    } else if ([ext.lowercaseString isEqualToString:@"ai"]) {
        return @"ic_company_cloud_ai";
    } else if ([ext.lowercaseString isEqualToString:@"xlsx"]) {
        return @"ic_company_cloud_excel";
    } else if ([ext.lowercaseString isEqualToString:@"mp3"]) {
        return @"ic_company_cloud_music";
    } else if ([ext.lowercaseString isEqualToString:@"zip"]) {
        return @"ic_company_cloud_package";
    } else if ([ext.lowercaseString isEqualToString:@"pdf"]) {
        return @"ic_company_cloud_pdf";
    } else if ([ext.lowercaseString isEqualToString:@"ppt"] || [ext.lowercaseString isEqualToString:@"pptx"]) {
        return @"ic_company_cloud_ppt";
    } else if ([ext.lowercaseString isEqualToString:@"ps"]) {
        return @"ic_company_cloud_ps";
    } else if ([ext.lowercaseString isEqualToString:@"sketch"]) {
        return @"ic_company_cloud_sketch";
    } else if ([ext.lowercaseString isEqualToString:@"mp4"]) {
        return @"ic_company_cloud_video";
    } else if ([ext.lowercaseString isEqualToString:@"docx"] || [ext.lowercaseString isEqualToString:@"doc"]) {
        return @"ic_company_cloud_word";
    } else if ([ext.lowercaseString isEqualToString:@"xd"]) {
        return @"ic_company_cloud_xd";
    } else {
        return @"ic_company_cloud_others";
    }
    
    return @"ic_photo_big_big";
}

/* 截取URL中的参数 */
- (NSMutableDictionary *)getURLParameters {
    
    // 查找参数
    NSRange range = [self rangeOfString:@"?"];
    if (range.location == NSNotFound) {
        return nil;
    }
    
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    
    // 截取参数
    NSString *parametersString = [self substringFromIndex:range.location + 1];
    
    // 判断参数是单个参数还是多个参数
    if ([parametersString containsString:@"&"]) {
        
        // 多个参数，分割参数
        NSArray *urlComponents = [parametersString componentsSeparatedByString:@"&"];
        
        for (NSString *keyValuePair in urlComponents) {
            // 生成Key/Value
            NSArray *pairComponents = [keyValuePair componentsSeparatedByString:@"="];
            NSString *key = [pairComponents.firstObject stringByRemovingPercentEncoding];
            NSString *value = [pairComponents.lastObject stringByRemovingPercentEncoding];
            
            // Key不能为nil
            if (key == nil || value == nil) {
                continue;
            }
            
            id existValue = [params valueForKey:key];
            
            if (existValue != nil) {
                
                // 已存在的值，生成数组
                if ([existValue isKindOfClass:[NSArray class]]) {
                    // 已存在的值生成数组
                    NSMutableArray *items = [NSMutableArray arrayWithArray:existValue];
                    [items addObject:value];
                    
                    [params setValue:items forKey:key];
                } else {
                    
                    // 非数组
                    [params setValue:@[existValue, value] forKey:key];
                }
                
            } else {
                
                // 设置值
                [params setValue:value forKey:key];
            }
        }
    } else {
        // 单个参数
        
        // 生成Key/Value
        NSArray *pairComponents = [parametersString componentsSeparatedByString:@"="];
        
        // 只有一个参数，没有值
        if (pairComponents.count == 1) {
            return nil;
        }
        
        // 分隔值
        NSString *key = [pairComponents.firstObject stringByRemovingPercentEncoding];
        NSString *value = [pairComponents.lastObject stringByRemovingPercentEncoding];
        
        // Key不能为nil
        if (key == nil || value == nil) {
            return nil;
        }
        
        // 设置值
        [params setValue:value forKey:key];
    }
    
    return params;
}
- (NSString *)translateXiaoShuDianWithFloat:(CGFloat)num
{
    NSString *finish = nil;
    NSString *floStr = [NSString stringWithFormat:@"%f",num];
    NSArray *numArray = [floStr componentsSeparatedByString:@"."];
    if([[numArray objectAtIndex:1] integerValue] == 0)
        {
        finish = numArray[0];
        }
    else
        {
        finish = [self bianliFromStr:floStr];
        }
    return finish;
    
}


- (NSString *)bianliFromStr:(NSString *)str
{
    if(![str hasSuffix:@"0"])
        {
        return str;
        }
    
    NSInteger strLength = str.length;
    NSString *string2 = [str substringWithRange:NSMakeRange(0, strLength-1)];
    return   [self bianliFromStr:string2];
    
    
}

-(BOOL)JudgeFirstIsLetter{
    
    NSString *regex =@"[A-Za-z]+";
    
    NSPredicate*predicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",regex];
    
    return [predicate evaluateWithObject:self];
    
}

/**
 基础方法
 
 @param regex 正则表达式
 @return 正则验证成功返回YES, 否则返回NO
 */
- (BOOL)isValidateByRegex:(NSString *)regex {
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",regex];
    return [predicate evaluateWithObject:self];
}

/**
 验证手机号码
 
 @return 正则验证成功返回YES, 否则返回NO
 */
- (BOOL)isMobileNumber {
    NSString *emailRegex = @"^1(3[0-9]|4[56789]|5[0-9]|6[6]|7[0-9]|8[0-9]|9[189])\\d{8}$";
    return [self isValidateByRegex:emailRegex];
}

/**
 判断运营商
 各个运营商开头号码不同 需要根据运营商更新
 
 @return  正则验证成功返回YES, 否则返回NO
 */
- (BOOL)isMobileNumberClassification {
    /**
     * 手机号码
     * 移动：134(0-8)、135、136、137、138、139、147、150、151、152、157、158、159、172、178、182、183、184、187、188、198
     *
     * 联通：130、131、132、145、155、156、166、175、176、185、186
     *
     * 电信：133、149、153、173、177、180、181、189、191、199
     *
     虚拟运营商
     电信：1700、1701、1702
     移动：1703、1705、1706
     联通：1704、1707、1708、1709、171
     卫星通信：1349
     */
    /**
     * 中国移动：China Mobile
     * 134(0-8)、135、136、137、138、139、147、150、151、152、157、158、159、172、178、182、183、184、187、188、198
     
     */
    NSString * CM = @"^1(34[0-8]|3[5-9]|47|5[0127-9]|8[23478]|98)\\d{8}$";
    /**
     * 中国联通：China Unicom
     * 130、131、132、145、155、156、166、175、176、185、186
     */
    NSString * CU = @"^1((3[0-2]|45|5[56]|166|7[56]|8[56]))\\d{8}$";
    /**
     * 中国电信：China Telecom
     * 133、149、153、173、177、180、181、189、191、199
     */
    NSString * CT = @"^1((33|49|53|7[37]|8[019]|9[19]))\\d{8}$";
    
    if ([self isValidateByRegex:CM]) {
        NSLog(@"手机运营商是====CM---中国移动");
        return YES;
    } else if ([self isValidateByRegex:CU]) {
        NSLog(@"手机运营商是====CU---中国联通");
        return YES;
    } else if ([self isValidateByRegex:CT]){
        NSLog(@"手机运营商是====CT---中国电信");
        return YES;
    } else {
        return NO;
    }
    
}

- (NSString*)decimalStringValue{
    NSString *doubleString = [NSString stringWithFormat:@"%lf", [self doubleValue]];
    NSArray <NSString*>*strAry = [doubleString componentsSeparatedByString:@"."];
    if (strAry.count >1 && strAry[1].length>=5) {
        NSDecimalNumber *formartDecimalStringr  = [NSDecimalNumber decimalNumberWithString:doubleString];
        return [formartDecimalStringr stringValue];
    }
    else{
        return [@"" translateXiaoShuDianWithFloat:[self floatValue]];
    }
}

/** 获取新UA */
+ (NSString *)getNewUserAgent
{

    NSString *language = [[NSUserDefaults standardUserDefaults] objectForKey:@"appLanguage"]?[[NSUserDefaults standardUserDefaults] objectForKey:@"appLanguage"]:@"ZH_CN";
    
    NSString *newUserAgent = [NSString stringWithFormat:@" Scheme/%@ %@/ios BuildMode/%@ language/%@",[WJCDeployModel getDeployWithDeployKey:WJCDeployAPPSchema],[[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleShortVersionString"],[WJCDeployModel getDeployWithDeployKey:WJCDeployEnv],language];
    
    return newUserAgent;
}
#define StringIsNullOrEmpty111(str) (str == nil || [str isEqualToString:@""])
- (CGRect)heightForStringSize:(CGSize)size Font:(UIFont *)font
{
    return [self heightForStringSize:size Font:font Lines:0];
}

- (CGRect)heightForStringSize:(CGSize)size Font:(UIFont *)font Lines:(NSInteger)lines
{
    if (StringIsNullOrEmpty111(self))
    {
        return CGRectMake(0, 0, 0, 0);
    }
    static UILabel *lbtext;
    if (lbtext == nil)
    {
        lbtext = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, size.width, 999999)];
    }
    else
    {
        lbtext.frame = CGRectMake(0, 0, size.width, 999999);
    }
    lbtext.font = font;
    lbtext.text = self;
    lbtext.numberOfLines = lines;
    CGRect rect = [lbtext textRectForBounds:lbtext.frame limitedToNumberOfLines:lines];
    if(rect.size.height < 0)
    {
        rect.size.height = 0;
    }
    if (rect.size.width < 0)
    {
        rect.size.width = 0;
    }
    return rect;
}
//根据字符串的高度/一行的高度 = 展示的行数
-(int)numberRowsStringSize:(CGSize)size font:(UIFont *)font Lines:(NSInteger)lines{
    CGFloat height1 = [self heightForStringSize:size Font:font Lines:lines].size.height;//[NSString heightForString:str Size:size Font:font].size.height;
    
    //得到一行的字体高度
    CGFloat height2 =  [self heightForStringSize:size Font:font Lines:1].size.height;
    int i = round(height1/height2);
    return i;
}
- (NSArray*)getURLFromSelfStr{
    NSError *error;
    //可以识别url的正则表达式
    NSString *regulaStr = @"((http[s]{0,1}|ftp)://[a-zA-Z0-9\\.\\-]+\\.([a-zA-Z]{2,4})(:\\d+)?(/[a-zA-Z0-9\\.\\-~!@#$%^&*+?:_/=<>]*)?)|(www.[a-zA-Z0-9\\.\\-]+\\.([a-zA-Z]{2,4})(:\\d+)?(/[a-zA-Z0-9\\.\\-~!@#$%^&*+?:_/=<>]*)?)";

    NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:regulaStr
    options:NSRegularExpressionCaseInsensitive
    error:&error];

    NSArray *arrayOfAllMatches = [regex matchesInString:self
    options:0
    range:NSMakeRange(0, [self length])];

    //NSString *subStr;
    NSMutableArray *arr=[[NSMutableArray alloc] init];

    for (NSTextCheckingResult *match in arrayOfAllMatches){
        NSString* substringForMatch;
        substringForMatch = [self substringWithRange:match.range];
        [arr addObject:substringForMatch];
    }
    return arr;
}
/**
 *判断一个字符串是否是一个IP地址
 **/
- (BOOL)isValidIP{
    NSString *ipStr = self;
    if (nil == ipStr) {
        return NO;
    }
    
    NSArray *ipArray = [ipStr componentsSeparatedByString:@"."];
    if (ipArray.count == 4) {
        for (NSString *ipnumberStr in ipArray) {
            int ipnumber = [ipnumberStr intValue];
            if (!(ipnumber>=0 && ipnumber<=255)) {
                return NO;
            }
        }
        return YES;
    }
    return NO;
}
+(NSString *)randomCarWithCount:(NSInteger)count{
    //定义一个包含数字，大小写字母的字符串
       NSString * strAll = @"0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
       //定义一个结果
       NSString * result = [[NSMutableString alloc]initWithCapacity:16];
       for (int i = 0; i < count; i++)
       {
           //获取随机数
           NSInteger index = arc4random() % (strAll.length-1);
           char tempStr = [strAll characterAtIndex:index];
           result = (NSMutableString *)[result stringByAppendingString:[NSString stringWithFormat:@"%c",tempStr]];
       }
       
       return result;
}

@end
